

package com.xielun.fly.framework.sql;

import com.xielun.fly.framework.Constants;
import net.minidev.json.JSONValue;

import java.sql.*;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


public class SQLExecutor {
    private static final String TAG = "SQLExecutor";


    static {
        try {//调用Class.forName()方法加载驱动程序
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取连接
     *
     * @return
     * @throws Exception
     */
    private synchronized Connection getConnection() throws Exception {
        return DriverManager.getConnection(SQLConfig.MYSQL_URI + "?useUnicode=true&characterEncoding=UTF-8&user="
                + SQLConfig.MYSQL_ACCOUNT + "&password=" + SQLConfig.MYSQL_PASSWORD);
    }


    private Connection connection;
    private Statement statement;
    private DatabaseMetaData metaData;

    /**
     * 关闭连接，释放资源
     */
    public void close() {
        try {
            if (statement != null && statement.isClosed() == false) {
                statement.close();
            }
            if (connection != null && connection.isClosed() == false) {
                connection.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        metaData = null;
        statement = null;
    }

    /**
     * 执行SQL
     *
     * @return
     * @throws Exception
     */
    public Object excute(SQL meta) throws Exception {
        final String sql = SQLBuilder.genSQL(meta);
        System.out.println(sql);
        Object result = null;
        String operate = null;//sql.getOprate();
        ResultSet rs = null;
        if (connection == null || connection.isClosed()) {
            connection = getConnection();
            statement = connection.createStatement(); //创建Statement对象
            metaData = connection.getMetaData();
        }
        if (meta.getOperate().equals(Constants.ADD)) {
            final long updateCount = statement.executeUpdate(sql);
            return new LinkedHashMap<String, Object>() {{
                put("sql", sql);
                put("result", updateCount);
            }};

        } else if (meta.getOperate().equals(Constants.DEL)) {
            //delete
            final long updateCount = statement.executeUpdate(sql);
            return new LinkedHashMap<String, Object>() {{
                put("sql", sql);
                put("result", updateCount);
            }};
        } else if (meta.getOperate().equals(Constants.MOD)) {
            //update
            final long updateCount = statement.executeUpdate(sql);
            return new LinkedHashMap<String, Object>() {{
                put("sql", sql);
                put("result", updateCount);
            }};
        } else {
            if (!meta.isDataArray()) {
                Map<String, Object> _result = new LinkedHashMap();
                rs = statement.executeQuery(sql);
                ResultSetMetaData resultMetaData = rs.getMetaData();

                List<String> columnNames = new ArrayList();
                for (int i = 1; i <= resultMetaData.getColumnCount(); i++) {
                    String columnName = resultMetaData.getColumnName(i);
                    columnNames.add(columnName);
                }
                if (rs.next()) {

                    for (String label : columnNames) {
                        _result.put(label, rs.getObject(label));
                    }
                }
                result = _result;
            } else {
                List<Map<String, Object>> _result = new ArrayList<Map<String, Object>>();
                rs = statement.executeQuery(sql);
                ResultSetMetaData resultMetaData = rs.getMetaData();

                List<String> columnNames = new ArrayList();
                for (int i = 1; i <= resultMetaData.getColumnCount(); i++) {
                    String columnName = resultMetaData.getColumnName(i);
                    columnNames.add(columnName);
                }

                while (rs.next()) {
                    Map<String, Object> obj = new LinkedHashMap();
                    for (String label : columnNames) {
                        obj.put(label, rs.getObject(label));
                    }
                    _result.add(obj);
                }
                result = _result;
            }
        }


        rs.close();

        return result;
    }





}
